#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - User Interface - User groups management 
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.join(DIR, "../core"))
import security
import exceptions
import usage
import tools
import users
     
def manageArgs(argc, argv):
    """Manages command line input.
    @param argc: Command line argument count
    @type argc: C{int}
    @param argv: Command line input data
    @type argv: C{list}"""
    if argc == 3 and sys.argv[2] == "list":
        print_user_group_list()
    elif argc == 4 and sys.argv[2] == "data":
        print_user_group_data(sys.argv[3])
    elif argc == 3 and sys.argv[2] == "add":
        add_user_group_interactively()
    elif argc > 3 and sys.argv[2] == "add":
         add_user_group(sys.argv)
    elif argc == 3 and sys.argv[2] == "mod":
        modify_user_group_interactively()
    elif argc > 3 and sys.argv[2] == "mod":
        modify_user_group(sys.argv)
    elif argc == 4 and sys.argv[2] == "del":
        delete_user_group(sys.argv[3], True)
    elif argc == 5 and sys.argv[2] == "del" and sys.argv[3] == "-f":
        delete_user_group(sys.argv[4], False)
    else:
        print usage.get_usage()
        
def print_user_group_list():
    """Prints the ID of every user group."""
    userGroupList = users.get_user_groups()
    for groupId in userGroupList:
        print groupId

def print_user_group_data(id):
    """Prints all fields of a user group.
    @param id: User group ID
    @type id: C{str}"""
    userGroupData = users.get_user_group_data(id)
    print "ID: %s" % userGroupData.get_id()
            
    name = userGroupData.get_name()
    if name == None or name == "": name = "<None>"
    print "NAME: %s" % name

def add_user_group_interactively():
    """Adds a new user group prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        id = raw_input("ID: ")
        ok = (id != None and id != "")
        if not ok: print "Data not valid, try again"
        
    name = raw_input("Name: ")
    if name == "": name = None
    
    group = users.UserGroup(id, name)
    users.add_user_group(group)
    print "User group added successfully"

def add_user_group(argv):
    """Adds a new user group.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    id = tools.get_parameter_value(argv, "id")
    if id == None or id == "": raise exceptions.Exception("User group ID not valid or not specified.")
    
    name = tools.get_parameter_value(argv, "n")
    
    group = users.UserGroup(id, name)
    users.add_user_group(group)
    print "User group added successfully"
    
def modify_user_group_interactively():
    """Modifies an existing user group prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        oldId = raw_input("Old ID: ")
        ok = (oldId != None and oldId != "")
        if not ok: print "Data not valid, try again"

    ok = False
    while (not ok):
        newId = raw_input("New ID: ")
        ok = (newId != None and newId != "")
        if not ok: print "Data not valid, try again"
        
    name = raw_input("Name: ")
    if name == "": name = None
    
    users.modify_user_group(oldId, newId, name)
    print "User group modified successfully"
    
def modify_user_group(argv):
    """Modifies an existing user group.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    oldId = tools.get_parameter_value(argv, "oid")
    if oldId == None or oldId == "": raise exceptions.Exception("User group old ID not valid or not specified")
    
    newId = tools.get_parameter_value(argv, "nid")
    if newId == None or newId == "": raise exceptions.Exception("User group new ID not valid or not specified")
    
    name = tools.get_parameter_value(argv, "n")
        
    users.modify_user_group(oldId, newId, name)
    print "User group modified successfully"    
    
def delete_user_group(id, confirm):
    """Deletes an existing user group.
    @param id: User group ID
    @type id: C{str}
    @param confirm: Determines if UI must prompt the user a confirmation.
    @type confirm: C{bool}"""
    security.check_root()
    
    if confirm:
        ok = False
        while (not ok):
            response = raw_input("Are you sure you want to delete user group '%s'? [y/n]: " % id)
            response = response.lower()
            ok = (response != None and response != "" and (response == "y" or response == "n"))
            if not ok: print "Answer not valid"
        if response == "n": 
            exit(0)
            
    users.delete_user_group(id)
    print "User group deleted successfully"
